package com.arrays;

public class SpiralMatrixII0126_59 {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int q = n/2;
        int starti = 0, startj=0,i = 0,j =0;
        int p =1;
        int count = 1;
        while (q>0){
            for (j = startj; j < n-p ; j++) {
                res[starti][j] = count;
                count++;
            }
            for (i = starti; i < n-p; i++) {
                res[i][j] =count;
                count++;
            }
            for ( ;  j> startj; j--) {
                res[i][j] = count;
                count++;
            }
            for ( ; i>starti ; i--) {
                res[i][j] = count;
                count++;
            }
            starti++;
            startj++;
            p++;
            q--;
        }
        if(n%2 == 1) res[starti][startj] = count;
        return res;
    }
}
